package cn.itsource.user.interceptor;

import cn.itsource.user.domain.LoginInfo;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            writeJson(response);
            return false;
        }
        LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get("token");
        if (loginInfo == null) {
            writeJson(response);
            return false;
        }
        redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
        return true;
    }


    private void writeJson(HttpServletResponse response) throws IOException {
        response.setContentType("text/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
    }

}
